package com.ricervcvcer.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ricervcvcer.common.util.ResultEntity;
import com.ricervcvcer.user.entity.SysGrpPer;
import com.ricervcvcer.user.service.ISysGrpPerService;
import com.ricervcvcer.user.util.RicervcvcerConstant;
import com.ricervcvcer.user.vo.MenuNode;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author moge
 * @since 2022-01-10
 */
@RestController
@RequestMapping("sys-grp-per")
public class SysGrpPerController {
    @Autowired
    ISysGrpPerService grpPerService;


    @ApiOperation("根据分组id获取对应的权限id")
    @GetMapping("getByGrpId/{id}")
    public ResultEntity getByGrpId(@ApiParam("分组id") @PathVariable Integer id) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("gf_grp_id", id);
        List<SysGrpPer> list = grpPerService.list(qw);
        return ResultEntity.successWithData(list);
    }


    @ApiOperation("重新给对应的角色分配菜单权限")
    @PutMapping("ids/{grpId}")
    @Transactional
    public ResultEntity update(
            @PathVariable Integer grpId,
            @RequestBody List<MenuNode> nodes){

        QueryWrapper qw=new QueryWrapper();
        qw.eq("gf_grp_id",grpId);
        // 查询是否有原来的权限
        List list = grpPerService.list(qw);

        boolean b1 = true;
        if(list.size()>0){
            // 删除原来的权限
            Map<String,Object> map=new HashMap<>();
            map.put("gf_grp_id", grpId);
            b1 = grpPerService.removeByMap(map);
        }

        // 把新权限添加
        List<SysGrpPer> srs = nodes.stream().filter(item->{
                    if(item.getRightType().equals(RicervcvcerConstant.PERMIS_REQUEST)){
                        return true;
                    }
                    return false;
                }).map((item) -> {
                    SysGrpPer s = new SysGrpPer();
                    s.setGfGrpId(grpId);
                    s.setGfPerId(Integer.parseInt(item.getRightCode()));
                    return s;
                }).collect(Collectors.toList());
        boolean b2 = grpPerService.saveBatch(srs);
        if(!(b1 && b2)){
            throw new RuntimeException(RicervcvcerConstant.UPDATE_ERROR);
        }

        // 刷新redis的权限
        return ResultEntity.successWithoutData();
    }
}
